import preprocess.Data2Feature as D2F
import operator
import numpy as np
import pandas as pd
from sklearn.linear_model import Perceptron
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder

NAME = 'PCT'

class Fit:
    
    N1 = 3
    N2 = 6
    Min_Web = 2
    Min_Title = 1
    Title =True
    Website = True
    Add = False
    Stopwords = True
    
    def __init__(self,X_train,Y_train,X_test,Y_test,CutMethod):
        self.predictions = self.fit(X_train,Y_train,X_test,Y_test,CutMethod)

    @staticmethod
    def refomat(X_features,Y):
        train_feature = X_features['train']
        train_category = Y['train']
        test_feature = X_features['test']
        test_category = Y['test']

        all_category = np.unique(np.hstack((train_category,test_category)))

        le = LabelEncoder()
        le.fit(all_category)

        train_category = le.transform(train_category)
        test_category = le.transform(test_category)

        return train_feature,test_feature,train_category,test_category,le


    def fit(self,X_train,Y_train,X_test,Y_test,CutMethod):


        X = {}
        X['train'] = X_train
        X['test'] = X_test
        Y = {}
        Y['train'] = Y_train
        Y['test'] = Y_test
        X_features = D2F.Data2Feature(X,self.N1,self.N2,
                                      website=self.Website,
                                      title=self.Title,
                                      cutmethod=CutMethod,
                                      add=self.Add,
                                      stopwords=self.Stopwords, 
                                      min_web=self.Min_Web,
                                      min_title=self.Min_Title).features
        [Train_feature,Test_feature,Train_category,Test_category,le] = Fit.refomat(X_features,Y)
        
        lin_clf = Perceptron(random_state=0)
        lin_clf.fit(Train_feature, Train_category) 
        
        Train_category_prediction = lin_clf.predict(Train_feature)
        print ('Perceptron : Traning Set Accuracy: %f' % accuracy_score(Train_category,Train_category_prediction))
        Test_category_prediction = lin_clf.predict(Test_feature)
        print ('Perceptron : Test Set Accuracy: %f' % accuracy_score(Test_category,Test_category_prediction))
        
        Y_test_prediction = le.inverse_transform(Test_category_prediction)
        
        return Y_test_prediction